package com.epoch.server.kernel.dao;

import com.epoch.common.User;
import com.epoch.common.UserRegister;
import com.epoch.server.kernel.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Seon
 * @date 2022/10/20 18:20
 */
public class UserDao {
    private static Connection conn = null;

    /**
     * 通过数据库进行注册信息
     */
    public boolean registerUser(UserRegister willRes) throws SQLException {
        boolean check = false;
        PreparedStatement ps;

        conn = DBUtil.getConnectDB();
        String sql = "insert into user (USERNAME, PASSWORD) values (?,?)";
        ps = conn.prepareStatement(sql);
        //赋值
        ps.setString(1,willRes.getName());
        ps.setString(2,willRes.getPassword());

        //对SQL语句进行处理
        int judge = ps.executeUpdate();
        //executeUpdate（） 返回值是更新的行数

        if (judge == 1) {
            check = true;
        }
        DBUtil.close(conn, ps, null);
        return check;
    }


    /**
     * 检查登录信息
     */
    public User userCheck(String name, String password) throws SQLException {
        boolean check = false;
        PreparedStatement ps = null;
        ResultSet res = null;

        conn = DBUtil.getConnectDB();
        String sql = "select id, username from user where username = ? and password = ?";
        ps = conn.prepareStatement(sql);
        ps.setString(1, name);
        ps.setString(2, password);
        //执行
        res = ps.executeQuery();

        if(res.next()) {
            int id = res.getInt(1);
            String username = res.getString(2);
            User user = new User();
            user.setId(id);
            user.setName(username);
            return user;
        }
        DBUtil.close(conn, ps, res);
        return null;
    }

}
